package com.ohuang.wallpapermanager.wallPaperService

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.service.wallpaper.WallpaperService
import android.util.Log
import android.view.SurfaceHolder
import com.ohuang.wallpapermanager.R
import com.ohuang.wallpapermanager.config.LocalConfig
import com.ohuang.wallpapermanager.util.BitMapUtil


class LockImageWallPaperService : WallpaperService() {
    val TAG = "LockImageWallPaperService"

    private var bitMap: Bitmap? = null
    private var bitMapLock: Bitmap? = null
    private var useWallPaperImagePath: String = ""
    private var useWallPaperImagePathLock: String = ""


    override fun onCreate() {
        super.onCreate()

    }


    override fun onCreateEngine(): Engine {
        return ImageEngine()
    }


    override fun onDestroy() {
        super.onDestroy()

        bitMap?.recycle()
        bitMapLock?.recycle()

    }

    private var defaultBitMap: Bitmap? = null


    private inner class ImageEngine : Engine() {


        private var holder: SurfaceHolder? = null

        private var handler = Handler(Looper.getMainLooper())

        var shouldShowLock: Boolean = false  //应该显示锁屏

        private var isCanvasSizeChange: Boolean = false


        private fun getDefaultBitMap(width: Int, height: Int): Bitmap? {
            if (defaultBitMap != null && !isCanvasSizeChange) {
                return defaultBitMap!!
            }
            var new: Bitmap? = null
            try {
                new = BitmapFactory.decodeResource(resources, R.drawable.defalut)
                defaultBitMap = BitMapUtil.cropBitmapToCenter(new, width, height)
                return defaultBitMap
            } catch (e: Exception) {
            } finally {
                new?.recycle()
            }
            return null
        }

        private val unlockReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent) {
                if (Intent.ACTION_USER_PRESENT == intent.action) {
                    // 设备已被解锁
                    if (shouldShowLock) {
                        shouldShowLock = false
                        draw()
                    }
                }
            }
        }


        override fun onCreate(surfaceHolder: SurfaceHolder) {
            super.onCreate(surfaceHolder)
            val filter = IntentFilter(Intent.ACTION_USER_PRESENT)
            registerReceiver(unlockReceiver, filter)
        }

        override fun onSurfaceCreated(holder: SurfaceHolder?) {
            super.onSurfaceCreated(holder)
        }


        override fun onVisibilityChanged(visible: Boolean) {
            super.onVisibilityChanged(visible)
            if (visible) {
                handler.post {
                    draw()
                }
            }
        }

        override fun onSurfaceChanged(
            holder: SurfaceHolder?,
            format: Int,
            width: Int,
            height: Int
        ) {
            super.onSurfaceChanged(holder, format, width, height)
            handler.post {
                this.holder = surfaceHolder
                setCanvasSize(width, height)
                draw()
            }
        }

        fun onDrawFrame(canvas: Canvas) {
            val wallPaperServiceShowMode = LocalConfig.wallPaperServiceShowMode


            if (wallPaperServiceShowMode == 1) { //一直显示锁屏
                drawLock(canvas)
            } else if (wallPaperServiceShowMode == 2) { //一直显示桌面
                drawHome(canvas)
            } else { //自动切换

                if (shouldShowLock) {
                    drawLock(canvas)
                } else {
                    drawHome(canvas)
                }
            }
            isCanvasSizeChange = false
        }

        private var lastWith: Int = 0
        private var lastHeight: Int = 0
        private fun setCanvasSize(width: Int, height: Int): Boolean {
            val isNoChange = lastWith == width && height == lastHeight
            isCanvasSizeChange = !isNoChange
            lastWith = width
            lastHeight = height
            return !isNoChange
        }


        private fun drawLock(canvas: Canvas) {
            getLockBitmap(canvas)
            if (bitMapLock != null) {
                canvas.drawBitmap(bitMapLock!!, 0f, 0f, Paint())
            }
        }

        private fun getLockBitmap(canvas: Canvas) {
            if (isCanvasSizeChange){
                bitMapLock?.recycle()
                bitMapLock = null
            }
            if (LocalConfig.useWallPaperImagePathLock.isNotEmpty() &&
                (isCanvasSizeChange || LocalConfig.useWallPaperImagePathLock != useWallPaperImagePathLock)
            ) {
                useWallPaperImagePathLock = LocalConfig.useWallPaperImagePathLock
                try {
                    val new = BitmapFactory.decodeFile(useWallPaperImagePathLock)
                    new?.let {
                        bitMapLock?.recycle()
                        bitMapLock = BitMapUtil.cropBitmapToCenter(new, canvas.width, canvas.height)
                        if (bitMapLock != new) {
                            new.recycle()
                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            if (bitMapLock == null) {
                bitMapLock = getDefaultBitMap(canvas.width, canvas.height)
            }
        }


        private fun drawHome(canvas: Canvas) {
            getHomeBitmap(canvas)
            if (bitMap != null) {
                canvas.drawBitmap(bitMap!!, 0f, 0f, Paint())
            }
        }

        private fun getHomeBitmap(canvas: Canvas) {
            if (isCanvasSizeChange){
                bitMap?.recycle()
                bitMap = null
            }
            if (
                LocalConfig.useWallPaperImagePath.isNotEmpty() &&
                (isCanvasSizeChange || LocalConfig.useWallPaperImagePath != useWallPaperImagePath)
            ) {
                useWallPaperImagePath = LocalConfig.useWallPaperImagePath
                try {
                    val new = BitmapFactory.decodeFile(useWallPaperImagePath)
                    new?.let {
                        bitMap?.recycle()
                        bitMap = BitMapUtil.cropBitmapToCenter(new, canvas.width, canvas.height)
                        if (bitMap != new) {
                            new.recycle()
                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            if (bitMap == null) {
                bitMap = getDefaultBitMap(canvas.width, canvas.height)
            }

        }


        override fun onCommand(
            action: String?,
            x: Int,
            y: Int,
            z: Int,
            extras: Bundle?,
            resultRequested: Boolean
        ): Bundle? {
            if ("android.wallpaper.goingtosleep" == action) {
                shouldShowLock = true
            } else if ("android.wallpaper.keyguardgoingaway" == action) {
                shouldShowLock = false
            }

            handler.post {
                draw()
            }

            return super.onCommand(action, x, y, z, extras, resultRequested)
        }

        private fun draw() {
            if (isVisible) {
                val surfaceHolder = surfaceHolder
                var canvas: Canvas? = null
                try {
                    canvas = surfaceHolder.lockCanvas()
                    if (canvas != null) {
                        onDrawFrame(canvas)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    if (canvas != null) {
                        try {
                            surfaceHolder.unlockCanvasAndPost(canvas)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }


        override fun onDestroy() {
            super.onDestroy()
            holder = null
            unregisterReceiver(unlockReceiver)
        }


    }


}